﻿using System;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Oryon.Extensions.Internet
{
    /// <summary>
    /// Common internet extensions
    /// </summary>
    public static class Functions
    {
        /// <summary>
        /// Get Feed Content in HTML format
        /// </summary>
        /// <param name="rssAddress">Feed source' s internet address</param>
        /// <returns>if succedded it returns feed content in HTML format</returns>
        public static string GetRSSFeed(this Uri rssAddress)
        {
            StringBuilder builder = new StringBuilder();
            XDocument rssFeed= null;

            try
            {
                rssFeed = XDocument.Load(rssAddress.ToString());
            }
            catch (Exception excp)
            {
                throw excp;
            }

            builder.AppendLine(
                string.Format("<b><a href='{0}'>{1}</a></b><br/>",
                rssFeed.Root.Element("channel").Element("link").Value,
                rssFeed.Root.Element("channel").Element("description").Value)
                );

            var posts = (from item in rssFeed.Descendants("item")
                         select new
                         {
                             Title=item.Element("title").Value,
                             Link=item.Element("link").Value,
                             PublishDate=item.Element("pubDate").Value
                         }
                       ).OrderByDescending(f=>f.PublishDate);

            foreach (var post in posts)
            {
                builder.AppendLine(
                    string.Format("<a href='{0}'>{1}[{2}]</a><br/>"
                    , post.Link
                    , post.Title
                    ,post.PublishDate.ToString())
                    );
            }

            return builder.ToString();            
        }
    }
}
